package com.yutel.phone.binh.ui;

import java.util.ArrayList;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.yutel.phone.binh.R;
import com.yutel.phone.binh.comm.BitmapManager;
import com.yutel.phone.binh.data.vo.Episode;
import com.yutel.phone.binh.data.vo.EpisodeSource;
import com.yutel.phone.binh.data.vo.EpisodeVideo;
import com.yutel.phone.binh.data.vo.VideoDetail;
import com.yutel.phone.binh.service.DetailService;
import com.yutel.phone.binh.service.EpisodeService;
import com.yutel.phone.binh.service.HomeService;
import com.yutel.phone.binh.service.ServiceReceiver;
import com.yutel.phone.binh.service.SyncService;

public class DetailActivity extends BaseActivity implements
		ServiceReceiver.Receiver {
	final static String TAG = "DetailActivity";
	private ServiceReceiver mReceiver;
	private TextView vid;
	private ImageView poster;
	private TextView name;
	private TextView info;
	private TextView score;
	private TextView update_info;
	private TextView tagSummer;
	private TextView tagActor;
	private TextView tagEpisode;
	private View frameSummer;
	private View frameActor;
	private View frameEpisode;
	private TextView summer;
	private ListView actor;
	// 播放源元素
	private Spinner source;
	private Spinner video;
	private ArrayAdapter<String> sourceAdapter;
	private ArrayAdapter<String> videoAdapter;
	private ArrayAdapter<String> episodeAdapter;
	private ListView list;
	private ProgressBar empty;
	private TextView emptyText;
	private BitmapManager bmpManager;
	private VideoDetail vd;
	private ArrayList<EpisodeSource> episodes;
	final private ArrayList<String> episodeArray = new ArrayList<String>();
	private boolean running = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.detail_layout);
		mReceiver = new ServiceReceiver(new Handler());
		mReceiver.setReceiver(this);
		//
		vid = (TextView) findViewById(R.id.vid);
		poster = (ImageView) findViewById(R.id.poster);
		name = (TextView) findViewById(R.id.name);
		info = (TextView) findViewById(R.id.info);
		score = (TextView) findViewById(R.id.score);
		update_info = (TextView) findViewById(R.id.update_info);
		tagSummer = (TextView) findViewById(R.id.tag_summer);
		tagActor = (TextView) findViewById(R.id.tag_actor);
		tagEpisode = (TextView) findViewById(R.id.tag_episode);
		frameSummer = (View) findViewById(R.id.frame_summer);
		frameActor = (View) findViewById(R.id.frame_actor);
		frameEpisode = (View) findViewById(R.id.frame_episode);
		tagSummer.setOnClickListener(tagListener);
		tagActor.setOnClickListener(tagListener);
		tagEpisode.setOnClickListener(tagListener);
		// 简介、导演／演员
		summer = (TextView) findViewById(R.id.summer);
		actor = (ListView) findViewById(R.id.actor);
		// 播放源
		source = (Spinner) findViewById(R.id.source);
		video = (Spinner) findViewById(R.id.video);
		list = (ListView) findViewById(android.R.id.list);
		empty = (ProgressBar) findViewById(android.R.id.empty);
		emptyText = (TextView) findViewById(R.id.emptyText);
		episodeAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, episodeArray);
		list.setAdapter(episodeAdapter);
		list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent intent = new Intent(DetailActivity.this,
						PlayerActivity.class);
				int s=source.getSelectedItemPosition();
				int v=video.getSelectedItemPosition();
				Log.i(TAG,"s="+s+",v="+v+",i="+position);
				Episode ep=episodes.get(s).getList().get(v).getList().get(position);
				intent.putExtra(Intent.EXTRA_TEXT, ep.getUrl());
				startActivity(intent);
			}
		});
		bmpManager = new BitmapManager(BitmapFactory.decodeResource(
				getResources(), R.drawable.empty_img));
		String mid = getIntent().getStringExtra(Intent.EXTRA_UID);
		if (mid != null && !"".equals(mid)) {
			Intent intent = new Intent(Intent.ACTION_SYNC, null, this,
					DetailService.class);
			intent.putExtra(SyncService.EXTRA_STATUS_RECEIVER, mReceiver);
			intent.putExtra(Intent.EXTRA_UID, mid);
			startService(intent);
		} else {
			finish();
		}
	}

	@Override
	public void onReceiveResult(int resultCode, Bundle resultData) {
		Log.i(TAG, "onReceiveResult=" + resultCode);
		switch (resultCode) {
		case HomeService.STATUS_RUNNING:
			break;
		case HomeService.STATUS_FINISHED:
			String key = resultData.getString(Intent.EXTRA_TEXT);
			Log.i(TAG, "STATUS_FINISHED=" + key);
			if (key != null && key.equals(DetailService.class.getSimpleName())) {
				ArrayList<VideoDetail> mDataList = (ArrayList<VideoDetail>) resultData
						.getSerializable(DetailService.class.getSimpleName());
				initDetail(mDataList);
			} else if (key != null
					&& key.equals(EpisodeService.class.getSimpleName())) {
				episodes = (ArrayList<EpisodeSource>) resultData
						.getSerializable(EpisodeService.class.getSimpleName());
				initEpisode();
			}
			break;
		case HomeService.STATUS_ERROR:
			String errokey = resultData.getString(Intent.EXTRA_TEXT);
			if (errokey != null
					&& errokey.equals(EpisodeService.class.getSimpleName())) {
				emptyText.setText(R.string.service_error);
				empty.setVisibility(View.GONE);
				list.setVisibility(View.GONE);
				emptyText.setVisibility(View.VISIBLE);
				source.setVisibility(View.GONE);
				video.setVisibility(View.GONE);
			}
			break;
		default:
			Log.w(TAG, "warring resultCode=" + resultCode);
		}
	}

	/**
	 * 初始化详情
	 * 
	 * @param mDataList
	 */
	private void initDetail(ArrayList<VideoDetail> mDataList) {
		if (mDataList != null && mDataList.size() > 0) {
			vd = mDataList.get(0);
			vid.setText(vd.getVid());
			name.setText(vd.getName());
			info.setText(vd.getCategoryName());
			score.setText(vd.getScore());
			if (vd.getPremiereDate() != null) {
				update_info
						.setText(vd.getArea() + " | " + vd.getPremiereDate());
			} else {
				update_info.setText(vd.getArea());
			}
			bmpManager.loadBitmap(vd.getPoster(), poster);
			// 简介
			summer.setText(vd.getSummer());
			// 导演／演员
			ArrayList<String> list = new ArrayList<String>();
			if (vd.getDirector() != null && vd.getDirector().size() > 0) {
				for (String item : vd.getDirector()) {
					list.add(item + "(导演)");
				}
			}
			if (vd.getActores() != null && vd.getActores().size() > 0) {
				list.addAll(vd.getActores());
			}
			ArrayAdapter adapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_list_item_1, list);
			actor.setAdapter(adapter);
			// 初始界面
			tagSummer.setTextColor(android.graphics.Color.RED);
			frameSummer.setVisibility(View.VISIBLE);
			frameActor.setVisibility(View.GONE);
			frameEpisode.setVisibility(View.GONE);
		}
	}

	private void initEpisode() {
		if (episodes != null) {
			String[] sourceArray = new String[episodes.size()];
			for (int i = 0; i < episodes.size(); i++) {
				sourceArray[i] = episodes.get(i).getTypeName();
			}
			sourceAdapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_spinner_item, sourceArray);
			sourceAdapter
					.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			source.setAdapter(sourceAdapter);
			source.setSelection(0);
			// 选择源后的操作
			source.setOnItemSelectedListener(new OnItemSelectedListener() {
				@Override
				public void onItemSelected(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					final EpisodeSource es = episodes.get(arg2);
					if (es != null && es.getList().size() > 0) {
						String[] videoArray = new String[es.getList().size()];
						for (int i = 0; i < es.getList().size(); i++) {
							videoArray[i] = es.getList().get(i).getName();
						}
						videoAdapter = new ArrayAdapter<String>(
								DetailActivity.this,
								android.R.layout.simple_spinner_item,
								videoArray);
						videoAdapter
								.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
						video.setAdapter(videoAdapter);
						video.setSelection(0);
						// 选择节目的操作
						video.setOnItemSelectedListener(new OnItemSelectedListener() {
							@Override
							public void onItemSelected(AdapterView<?> arg0,
									View arg1, int arg2, long arg3) {
								EpisodeVideo ev = es.getList().get(arg2);
								if (ev != null) {
									episodeArray.clear();
									for (int i = 0; i < ev.getList().size(); i++) {
										episodeArray.add(ev.getList().get(i)
												.getName());
									}
									episodeAdapter.notifyDataSetChanged();
								}
							}

							@Override
							public void onNothingSelected(AdapterView<?> arg0) {
							}
						});
					}
				}

				@Override
				public void onNothingSelected(AdapterView<?> arg0) {
				}
			});
			empty.setVisibility(View.GONE);
			list.setVisibility(View.VISIBLE);
			emptyText.setVisibility(View.GONE);
			running = false;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, "Share");
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 0:
			if (vd != null && episodes != null) {
				StringBuffer sb = new StringBuffer();
				sb.append(vd.getCategoryName()).append(":")
						.append(vd.getName());
				int s = source.getSelectedItemPosition();
				int v = video.getSelectedItemPosition();
				EpisodeSource es = episodes.get(s);
				if (es != null && es.getList() != null) {
					EpisodeVideo ev = es.getList().get(v);
					if (es != null && es.getList() != null) {
						sb.append("\n").append(es.getTypeName()).append("、地址：");
						sb.append(ev.getList().get(0).getUrl());
					}
				}
				Intent intent = new Intent(Intent.ACTION_SEND);
				intent.setType("text/plain");
				intent.putExtra(Intent.EXTRA_SUBJECT, "分享到");
				intent.putExtra(Intent.EXTRA_TEXT, sb.toString());
				startActivity(Intent.createChooser(intent, getTitle()));
			} else {
				Toast.makeText(this, "播放源没有查到，请稍等再试", Toast.LENGTH_SHORT)
						.show();
			}
			break;
		default:
			Log.e(TAG, "default=" + item.getItemId());
		}
		return true;
	}

	OnClickListener tagListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.tag_summer:
				Log.i(TAG, "tagSummer click");
				tagSummer.setTextColor(android.graphics.Color.RED);
				tagActor.setTextColor(android.graphics.Color.WHITE);
				tagEpisode.setTextColor(android.graphics.Color.WHITE);
				frameSummer.setVisibility(View.VISIBLE);
				frameActor.setVisibility(View.GONE);
				frameEpisode.setVisibility(View.GONE);
				break;
			case R.id.tag_actor:
				Log.i(TAG, "tagActor click");
				tagSummer.setTextColor(android.graphics.Color.WHITE);
				tagActor.setTextColor(android.graphics.Color.RED);
				tagEpisode.setTextColor(android.graphics.Color.WHITE);
				frameSummer.setVisibility(View.GONE);
				frameActor.setVisibility(View.VISIBLE);
				frameEpisode.setVisibility(View.GONE);
				break;
			case R.id.tag_episode:
				Log.i(TAG, "tagEpisode click,running=" + running);
				if (!running && vd != null && episodes == null) {
					running = true;
					Intent intent = new Intent(Intent.ACTION_SYNC, null,
							DetailActivity.this, EpisodeService.class);
					intent.putExtra(SyncService.EXTRA_STATUS_RECEIVER,
							mReceiver);
					intent.putExtra("videoId", vd.getVid());
					startService(intent);
					empty.setVisibility(View.VISIBLE);
					list.setVisibility(View.GONE);
					emptyText.setVisibility(View.GONE);
				}
				tagSummer.setTextColor(android.graphics.Color.WHITE);
				tagActor.setTextColor(android.graphics.Color.WHITE);
				tagEpisode.setTextColor(android.graphics.Color.RED);
				frameSummer.setVisibility(View.GONE);
				frameActor.setVisibility(View.GONE);
				frameEpisode.setVisibility(View.VISIBLE);
				break;
			default:
				break;
			}
		}
	};
}